const app = getApp();
import {
  request
} from "../../utils/request";

Page({
  data: {
    tabList: {
      records: [],
      size: 10,
      current: 1,
      pages: 1,
      loading: false,
      finished: false
    },
    user: {
      avatar: "",
      inviterCode: "",
      nickname: "",
      points: 100,
    },
    inviterCode: "",
    openid: "",
    active: 0, // tab默认选中第一个
    show: false,
  },
  
  copyInviteCode() {
    const code = this.data.user.inviterCode;
    if (!code) return;

    wx.setClipboardData({
      data: code,
      success() {
        wx.showToast({
          title: '已复制邀请码',
          icon: 'success',
          duration: 1500
        });
      }
    });
  },

  onTabChange(event) {
    this.data.tabList.current = 1;
    this.data.tabList.pages = 1;
    this.data.tabList.records = [];
    this.data.tabList.loading = false;
    this.data.tabList.finished = false;
    this.setData({
      active: event.detail.index
    });
    this.loadData();
  },

  showPopup() {
    this.setData({
      show: true
    });
  },

  fillIn() {
    request({
        url: `user/fill-in/${this.data.inviterCode}/${this.data.openid}`,
        method: "GET"
      })
      .then(res => {
        wx.showToast({
          title: '填写成功',
          icon: 'success',
          duration: 1000,
          success: () => {
            setTimeout(() => {
              this.setData({
                show: false
              });
            }, 1000);
          }
        });
      })
      .catch(err => {
        console.error("填写邀请码失败", err);
        this.setData({
          show: false
        });
      });
  },

  // 加载数据方法
  loadData() {
    const listData = this.data.tabList;
    if (listData.loading || listData.finished) return;
    this.setData({
      'tabList.loading': true
    });
    const postData = {
      current: listData.current,
      size: listData.size,
      openid: this.data.openid
    };

    let postUrl = "";
    if(this.data.active === 0) {
      postUrl = "user-points/my-points";
    }else{
      postUrl = "user/my-inviter";
    }
    request({
        url: postUrl,
        method: "POST",
        data: postData,
        pageCtx: this,
        complete: () => {
          this.setData({
            loading: false
          });
        }
      })
      .then((res) => {
        const result = res;
        const newRecords = result.records || [];

        this.setData({
          tabList: {
            ...this.data.tabList,
            records: this.data.tabList.records.concat(newRecords),
            pages: result.pages, // 更新总页数
            loading: false,
            finished: this.data.tabList.current >= result.pages // 判断是否最后一页
          }
        });
      })
      .catch(err => console.error("查询列表失败", err));
  },



  // 触底事件（页面配置 onReachBottom）
  onReachBottom() {
    if (this.data.tabList.current < this.data.tabList.pages) {
      this.setData({
        'tabList.current': this.data.tabList.current + 1
      });
      this.loadData();
    }

    // const listData = this.data.tabList;
    // if (!listData.loading && !listData.finished) {
    //   this.setData({
    //     'tabList.current': listData.current + 1
    //   }, () => {
    //     this.loadData();
    //   });
    // }
  },
  onClose() {
    this.setData({
      show: false
    });
  },

  onLoad(options) {
    if (app.globalData.openid) {
      this.setData({
        openid: app.globalData.openid
      });
    }
    this.loadData();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    request({
        url: `user/info/${this.data.openid}`,
        method: "GET",
        pageCtx: this
      })
      .then(res => {
        this.setData({
          user: {
            avatar: res.avatar,
            inviterCode: res.inviterCode,
            nickname: res.nickname,
            points: res.points,
          }
        });
      })
      .catch(err => console.error("查询用户数据失败", err));
  },

})